package com.itheima.sync.controller;

import com.itheima.common.vo.ResultVo;
import com.itheima.sync.service.ArticleService;
import com.itheima.sync.util.SyncUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.concurrent.CountDownLatch;

@RestController
@RequestMapping("/sync")
@Slf4j
public class SyncController {
    @Autowired
    private ArticleService articleService;
    //这个可以调整
    private static final Long size = 5000L;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private String endTimeStr = null;



    //多线程方式进行导入

    /**
     * 此方法 需要拥有超级管理员的身份人进行操作
     *
     * @return
     */
    @GetMapping("/importAll")
    public ResultVo importAll() {

        Long startTime = System.currentTimeMillis();
        LocalDateTime now = LocalDateTime.now(ZoneId.systemDefault());
        String startTimeStr = now.format(SyncUtil.FORMATTER_YMDHMS);
        log.info("全量同步start：{}",startTimeStr);
        Boolean flag = stringRedisTemplate.opsForValue()
                .setIfAbsent("recordTime",
                    startTimeStr);
        log.info("全量同步start：{}, redisFlag={}",startTimeStr, flag);
        if (flag) {
            try {
                SyncUtil.sync_status = true;
                //1.查询统计所有数量
                Long total = articleService.selectCount(now);
                Long totalPages = total % size > 0 ? (total / size) + 1 : total / size;
                final CountDownLatch countDownLatch = new CountDownLatch(totalPages.intValue());
                //2.执行多线程方法

                for (Long page = 1L; page <= totalPages; page++) {
                    articleService.importAll(page, size, countDownLatch,now);
                }
                //3.设置等待 等到 CountDownLatch中的数量减为0之后执行
                try {
                    countDownLatch.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                SyncUtil.sync_status = false;
            }
            catch (Exception e){
                log.error("全量同步error：{}, redisFlag={}",startTimeStr, flag, e);
                return ResultVo.bizError("发生异常了: " + e.getMessage());
            }
            Long endTime = System.currentTimeMillis();
            endTimeStr = now.format(SyncUtil.FORMATTER_YMDHMS);
            log.info("全量同步end：{}, redisFlag={},cost={}",startTimeStr, flag,(endTime - startTime));
        } else {
            return ResultVo.ok("正在执行中....");
        }
        return ResultVo.ok("全量同步已完成了,start=" + startTimeStr + ",end=" + endTimeStr);
    }

    public static void main(String[] args) {
        String format = LocalDateTime.now(ZoneId.systemDefault()).format(SyncUtil.FORMATTER_YMDHMS);
        System.out.println(format);
    }
}
